import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { RescueInfo } from '../../entities/RescueInfo.entity'
import { RescueRecord } from '../../entities/RescueRecord.entity'
import { Users } from '../../entities/Users.entity'
import dayjs from 'dayjs'

@Provide()
export class RescueInfoService {
  @InjectEntityModel(RescueInfo)
  repo!: Repository<RescueInfo>

  @InjectEntityModel(RescueRecord)
  recordRepo!: Repository<RescueRecord>

  @InjectEntityModel(Users)
  userRepo!: Repository<Users>

  // 添加帮扶需求
  async addRescueInfo(data: {
    userId: string
    address: string
    content: string
    img: string[]
    lat: number
    lng: number
    childId: string
  }) {
    // 将图片数组转换为字符串（逗号分隔）
    const imgString = data.img.join(',')

    // 创建救助信息
    const rescueInfo = this.repo.create({
      name: '帮扶需求',
      childId: parseInt(data.childId),
      guardianId: parseInt(data.userId),
      rescueStatus: 1, // 1=待处
      rescueContent: data.content,
      rescueImg: imgString,
      address: data.address,
      lat: data.lat,
      lng: data.lng,
      createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
    })

    return await this.repo.save(rescueInfo)
  }

  // 获取用户的帮扶需求列表
  async getUserRescueInfos(userId: string = '0', page: number = 1, pageSize: number = 10) {
    const queryBuilder = this.repo.createQueryBuilder('ri')
      .leftJoin('ri.child', 'c')
      .leftJoin('ri.guardian', 'u')
      .select([
        'ri.id AS id',
        'ri.createTime AS createTime',
        'ri.name AS name',
        'ri.rescueStatus AS rescueStatus',
        'ri.rescueContent AS rescueContent',
        'ri.rescueImg AS rescueImg',
        'ri.address AS address',
        'ri.lat AS lat',
        'ri.lng AS lng',
        'c.name AS childName',
        'u.avatar AS guardianAvatar',
        'u.nickname AS guardianNickname'
      ])
      .orderBy('ri.createTime', 'DESC')
      
    if (userId !== '0') {
      queryBuilder.where('ri.guardianId = :userId', { userId: parseInt(userId) })
    }

    // 获取总数
    const total = await queryBuilder.getCount()
    
    // 获取分页数据
    const items = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getRawMany()

    // 处理图片字段（将字符串转换为数组）
    const processedItems = items.map(item => ({
      ...item,
      rescueImg: item.rescueImg ? item.rescueImg.split(',') : []
    }))

    return {
      total,
      items: processedItems,
    }
  }

  // 获取帮扶需求详情
  async getRescueInfoDetail(id: number) {
    const queryBuilder = this.repo.createQueryBuilder('ri')
      .leftJoin('ri.child', 'c')
      .leftJoin('ri.guardian', 'u')
      .select([
        'ri.id AS id',
        'ri.createTime AS createTime',
        'ri.name AS name',
        'ri.rescueType AS rescueType',
        'ri.rescueStatus AS rescueStatus',
        'ri.rescueContent AS rescueContent',
        'ri.rescueImg AS rescueImg',
        'ri.address AS address',
        'ri.lat AS lat',
        'ri.lng AS lng',
        'c.name AS childName',
        'c.avatar AS childAvatar',
        'c.birthday AS childBirthday',
        'c.gender AS childGender',
        'u.nickname AS guardianNickname',
        'u.phone AS guardianPhone',
        'u.avatar AS guardianAvatar'
      ])
      .where('ri.id = :id', { id })

    const result = await queryBuilder.getRawOne()

    if (!result) {
      throw new Error('帮扶需求不存在')
    }

    // 处理图片字段
    return {
      ...result,
      rescueImg: result.rescueImg ? result.rescueImg.split(',') : []
    }
  }

  // 添加帮扶记录
  async addRescueRecord(data: {
    userId: string
    rescueInfoId: number
  }) {
    // 检查帮扶需求是否存在
    const rescueInfo = await this.repo.findOne({
      where: { id: data.rescueInfoId }
    })

    if (!rescueInfo) {
      throw new Error('帮扶需求不存在')
    }

    // 检查是否已经帮扶过
    const existingRecord = await this.recordRepo.findOne({
      where: { 
        userId: parseInt(data.userId), 
        itemId: data.rescueInfoId 
      }
    })

    if (existingRecord) {
      throw new Error('您已经帮扶过啦')
    }

    // 创建帮扶记录
    const record = this.recordRepo.create({
      userId: parseInt(data.userId),
      itemId: data.rescueInfoId
    })

    const savedRecord = await this.recordRepo.save(record)

    // 更新用户证书类型，添加救助证书标识"1"
    await this.updateUserCertificateTypes(parseInt(data.userId), '1')

    return savedRecord
  }

  // 更新用户证书类型
  private async updateUserCertificateTypes(userId: number, certificateType: string) {
    const user = await this.userRepo.findOne({ where: { id: userId.toString() } })
    
    if (!user) {
      return
    }

    let certificateTypes = user.certificateTypes || ''
    const typesArray = certificateTypes ? certificateTypes.split(',') : []
    
    // 如果该类型不存在，则添加
    if (!typesArray.includes(certificateType)) {
      typesArray.push(certificateType)
      certificateTypes = typesArray.join(',')
      
      await this.userRepo.update(userId.toString(), { certificateTypes })
    }
  }

  // 获取帮扶需求的帮扶记录列表
  async getRescueRecords(rescueInfoId: number, page: number = 1, pageSize: number = 10) {
    const queryBuilder = this.recordRepo.createQueryBuilder('rr')
      .leftJoin('rr.user', 'u')
      .select([
        'rr.id AS id',
        'rr.createTime AS createTime',
        'rr.userId AS userId',
        'u.nickname AS userNickname',
        'u.avatar AS userAvatar',
        'u.phone AS userPhone'
      ])
      .where('rr.itemId = :rescueInfoId', { rescueInfoId })
      .orderBy('rr.createTime', 'DESC')

    // 获取总数
    const total = await queryBuilder.getCount()
    
    // 获取分页数据
    const items = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getRawMany()

    return {
      total,
      items,
    }
  }

  // 获取帮扶记录需求信息（帮扶人数、帮扶结束时间、发起人昵称、帮扶图片）
  async getRescueRecordInfo() {
    // 获取所有的帮扶记录
    const records = await this.recordRepo.find()
    // 取出所有的需求id
    const rescueInfoIds = records.map(record => record.itemId)
    // 去重
    const uniqueRescueInfoIds = [...new Set(rescueInfoIds)]
    // 根据id查询需求信息
    const queryBuilder = this.repo.createQueryBuilder('ri')
      .select([
        'ri.id AS id',
        'ri.name AS name',
        'ri.rescueStatus AS rescueStatus',
        'ri.rescueContent AS rescueContent',
        'ri.rescueImg AS rescueImg',
        'ri.address AS address',
        'ri.lat AS lat',
        'ri.lng AS lng',
        'ri.endTime AS endTime',
        'ri.guardianId AS guardianId'
      ])
      .where('ri.id IN (:...ids)', { ids: uniqueRescueInfoIds })
      // 连接用户表，查询发起人昵称
      .leftJoin('ri.guardian', 'u')
      .addSelect('u.nickname AS guardianNickname')
      .addSelect('u.avatar AS guardianAvatar')
      .orderBy('ri.createTime', 'DESC')
    // 查询结果
    const rescueInfos = await queryBuilder.getRawMany()
    // 统计帮扶人数
    const ans = rescueInfos.map(item => {
      const count = records.filter(record => record.itemId === item.id).length
      return {
        ...item,
        rescueImg: item.rescueImg ? item.rescueImg.split(', ') : [],
        count
      }
    })

    return {
      items: ans,
      total: ans.length
    }
  }

  // 检查用户是否有帮扶记录，并返回最近一次帮扶时间
  async checkUserHasRescued(userId: number): Promise<{ hasRescued: boolean; lastRescueTime: Date | null }> {
    const latestRecord = await this.recordRepo.findOne({
      where: { userId },
      order: { createTime: 'DESC' }
    })
    
    return {
      hasRescued: !!latestRecord,
      lastRescueTime: latestRecord?.createTime || null
    }
  }
}